package features.advance.jdk.io.unblocking;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author LIN
 * @date 2021-06-05
 */
public class UnBlockIO {
    public static void main(String[] args) throws Exception{

        DefaultSocketHandler defaultSocketHandler = new DefaultSocketHandler();
        Selector selector;
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            //设为noblocking
            serverSocketChannel.configureBlocking(false);

            SocketAddress socketAddress = new InetSocketAddress(8080);
            serverSocketChannel.bind(socketAddress);

            selector = Selector.open();

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }

        // 尝试多路复用选择器选择,如果没有Ready时间发生，则一直阻塞
        while (selector.select()>0){

            Set<SelectionKey> selectionKeySet = selector.selectedKeys();

            for (SelectionKey selectionKey : selectionKeySet) {
                // server socket 准备好接受连接，获取连接
                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel =((ServerSocketChannel)selectionKey.channel()).accept();
                    if(null != socketChannel){
                        //监听读写
                        socketChannel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    }
                }

                // socket 数据可读
                if(selectionKey.isReadable()){
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(5000);
                    socketChannel.read(buffer);
                    defaultSocketHandler.onReceiveData(buffer,socketChannel);
                }

                // socket 数据可写
                if(selectionKey.isWritable()){
                    ByteBuffer buffer = ByteBuffer.allocate(5000);
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    //处理数据写入请求
                    defaultSocketHandler.onReadySendData(buffer,socketChannel);
                }
            }
        }
    }
}
